<!-- src/views/system/AuthManagement.vue -->
<template>
  <div class="auth-management">
    <el-card class="auth-card">
      <template #header>
        <div class="card-header">
          <span>权限管理</span>
        </div>
      </template>

      <el-tabs v-model="activeTab" type="card">
        <!-- 用户角色分配 -->
        <el-tab-pane label="用户角色分配" name="userRole">
          <el-card class="inner-card">
            <el-form :model="userRoleForm" label-width="120px">
              <el-form-item label="用户ID">
                <el-input v-model="userRoleForm.userId" placeholder="请输入用户ID" />
              </el-form-item>
              <el-form-item label="角色">
                <el-select
                  v-model="userRoleForm.roleIds"
                  multiple
                  placeholder="请选择角色"
                  style="width: 100%"
                >
                  <el-option
                    v-for="role in roleOptions"
                    :key="role.id"
                    :label="role.name"
                    :value="role.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="assignUserRoles">分配角色</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- 角色权限分配 -->
        <el-tab-pane label="角色权限分配" name="rolePermission">
          <el-card class="inner-card">
            <el-form :model="rolePermissionForm" label-width="120px">
              <el-form-item label="角色">
                <el-select
                  v-model="rolePermissionForm.roleId"
                  placeholder="请选择角色"
                  style="width: 100%"
                  @change="loadRolePermissions"
                >
                  <el-option
                    v-for="role in roleOptions"
                    :key="role.id"
                    :label="role.name"
                    :value="role.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="权限点">
                <el-tree
                  ref="permissionTreeRef"
                  :data="permissionTreeData"
                  show-checkbox
                  node-key="id"
                  :props="defaultProps"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="assignRolePermissions">保存权限</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- 数据权限配置 -->
        <el-tab-pane label="数据权限配置" name="dataScope">
          <el-card class="inner-card">
            <el-form :model="dataScopeForm" label-width="120px">
              <el-form-item label="角色">
                <el-select
                  v-model="dataScopeForm.roleId"
                  placeholder="请选择角色"
                  style="width: 100%"
                  @change="loadRoleDataScope"
                >
                  <el-option
                    v-for="role in roleOptions"
                    :key="role.id"
                    :label="role.name"
                    :value="role.id"
                  />
                </el-select>
              </el-form-item>
              <el-form-item label="数据范围">
                <el-radio-group v-model="dataScopeForm.dataScope">
                  <el-radio :label="1">全部数据权限</el-radio>
                  <el-radio :label="2">自定义数据权限</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item v-if="dataScopeForm.dataScope === 2" label="部门">
                <el-tree
                  ref="deptTreeRef"
                  :data="deptTreeData"
                  show-checkbox
                  node-key="id"
                  :props="deptTreeProps"
                  style="width: 100%"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="saveDataScope">保存配置</el-button>
              </el-form-item>
            </el-form>
          </el-card>
        </el-tab-pane>

        <!-- 权限回收审计 -->
        <el-tab-pane label="权限回收审计" name="recycleLog">
          <el-card class="inner-card">
            <el-form :model="logQuery" label-width="80px" inline>
              <el-form-item label="操作人">
                <el-input v-model="logQuery.operator" placeholder="操作人" />
              </el-form-item>
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="logQuery.dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                />
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="queryRecycleLogs">查询</el-button>
              </el-form-item>
            </el-form>

            <el-table :data="recycleLogs" border style="width: 100%; margin-top: 20px;">
              <el-table-column prop="operator" label="操作人" />
              <el-table-column prop="operation" label="操作类型" />
              <el-table-column prop="target" label="操作对象" />
              <el-table-column prop="time" label="操作时间" />
              <el-table-column prop="details" label="详情" />
            </el-table>

            <el-pagination
              layout="prev, pager, next"
              :total="logTotal"
              :current-page="logQuery.page"
              @current-change="handlePageChange"
              style="margin-top: 20px; text-align: right;"
            />
          </el-card>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <el-card class="auth-card" style="margin-top: 20px;">
      <template #header>
        <div class="card-header">
          <span>系统操作</span>
        </div>
      </template>
      <div style="text-align: center;">
        <el-button type="warning" @click="refreshAuthCache">刷新权限缓存</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useAuthStore } from '@/stores/authStore'
import { useDeptStore } from '@/stores/deptStore'
import { ElMessage } from 'element-plus'

// 状态管理
const authStore = useAuthStore()
const deptStore = useDeptStore()
const activeTab = ref('userRole')

// 表单数据
const userRoleForm = reactive({
  userId: '',
  roleIds: []
})

const rolePermissionForm = reactive({
  roleId: ''
})

const dataScopeForm = reactive({
  roleId: '',
  dataScope: 1
})

const logQuery = reactive({
  operator: '',
  dateRange: [],
  page: 1,
  size: 10
})

// 选项数据
const roleOptions = ref([])
const permissionTreeData = ref([])
const deptTreeData = ref([])
const recycleLogs = ref([])
const logTotal = ref(0)

// 树形组件属性
const defaultProps = {
  children: 'children',
  label: 'label'
}

// 部门树属性 (适配部门数据结构)
const deptTreeProps = {
  children: 'children',
  label: 'name'
}

// 组件引用
const permissionTreeRef = ref(null)
const deptTreeRef = ref(null)

// 加载角色选项
const loadRoles = async () => {
  try {
    // 这里应该调用获取角色列表的API
    // 暂时使用模拟数据
    roleOptions.value = [
      { id: 1, name: '系统管理员' },
      { id: 2, name: '部门经理' },
      { id: 3, name: '普通员工' }
    ]
  } catch (error) {
    ElMessage.error('加载角色列表失败')
  }
}

// 加载权限树
const loadPermissions = async () => {
  try {
    // 这里应该调用获取权限列表的API
    // 暂时使用模拟数据
    permissionTreeData.value = [
      {
        id: 1,
        label: '系统管理',
        children: [
          { id: 11, label: '用户管理' },
          { id: 12, label: '角色管理' },
          { id: 13, label: '菜单管理' }
        ]
      },
      {
        id: 2,
        label: '业务管理',
        children: [
          { id: 21, label: '合同管理' },
          { id: 22, label: '案件管理' }
        ]
      }
    ]
  } catch (error) {
    ElMessage.error('加载权限列表失败')
  }
}

// 加载部门树 (使用deptStore)
const loadDepartments = async () => {
  try {
    await deptStore.getDeptTree()
    deptTreeData.value = deptStore.deptTree
  } catch (error) {
    ElMessage.error('加载部门树失败')
  }
}

// 加载角色已有权限
const loadRolePermissions = async (roleId) => {
  if (!roleId) return

  try {
    const res = await authStore.fetchUserPermissions({ userId: roleId })
    // 设置选中的权限节点
    // 这里需要根据实际返回数据结构调整
    const permissionIds = res.data.permissions.map(p => p.id)
    permissionTreeRef.value.setCheckedKeys(permissionIds)
  } catch (error) {
    ElMessage.error('加载角色权限失败')
  }
}

// 加载角色数据权限范围
const loadRoleDataScope = async (roleId) => {
  if (!roleId) return

  try {
    // 这里应该调用获取角色数据权限的API
    // 暂时使用模拟逻辑
    dataScopeForm.dataScope = 1 // 默认全部权限
  } catch (error) {
    ElMessage.error('加载角色数据权限失败')
  }
}

// 分配用户角色
const assignUserRoles = async () => {
  if (!userRoleForm.userId || !userRoleForm.roleIds.length) {
    ElMessage.warning('请填写完整信息')
    return
  }

  try {
    await authStore.assignUserRoles({
      userId: userRoleForm.userId,
      roleIds: userRoleForm.roleIds
    })
    ElMessage.success('角色分配成功')
  } catch (error) {
    ElMessage.error('角色分配失败')
  }
}

// 分配角色权限
const assignRolePermissions = async () => {
  if (!rolePermissionForm.roleId) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    const checkedKeys = permissionTreeRef.value.getCheckedKeys()
    await authStore.assignRoleAcls({
      roleId: rolePermissionForm.roleId,
      permissionIds: checkedKeys
    })
    ElMessage.success('权限分配成功')
  } catch (error) {
    ElMessage.error('权限分配失败')
  }
}

// 保存数据权限配置
const saveDataScope = async () => {
  if (!dataScopeForm.roleId) {
    ElMessage.warning('请选择角色')
    return
  }

  try {
    let deptIds = []
    if (dataScopeForm.dataScope === 2) {
      deptIds = deptTreeRef.value.getCheckedKeys()
    }

    await authStore.configureDataScope({
      roleId: dataScopeForm.roleId,
      dataScope: dataScopeForm.dataScope,
      deptIds
    })
    ElMessage.success('数据权限配置保存成功')
  } catch (error) {
    ElMessage.error('数据权限配置保存失败')
  }
}

// 查询回收日志
const queryRecycleLogs = async () => {
  try {
    const res = await authStore.getPermissionRecycleLogs({
      ...logQuery,
      startDate: logQuery.dateRange[0],
      endDate: logQuery.dateRange[1]
    })
    recycleLogs.value = res.data.logs
    logTotal.value = res.data.total
  } catch (error) {
    ElMessage.error('查询回收日志失败')
  }
}

// 刷新权限缓存
const refreshAuthCache = async () => {
  try {
    await authStore.refreshAuthCache()
    ElMessage.success('权限缓存刷新成功')
  } catch (error) {
    ElMessage.error('权限缓存刷新失败')
  }
}

// 处理分页变化
const handlePageChange = (page) => {
  logQuery.page = page
  queryRecycleLogs()
}

// 初始化数据
onMounted(async () => {
  await Promise.all([
    loadRoles(),
    loadPermissions(),
    loadDepartments()
  ])
})
</script>

<style scoped>
.auth-management {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 120px);
}

.auth-card {
  margin-bottom: 20px;
  border: none;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  font-weight: bold;
  color: #1e88e5;
  font-size: 18px;
}

.inner-card {
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

:deep(.el-tabs__item.is-active) {
  background-color: #1e88e5;
  color: white;
}

:deep(.el-tabs__item) {
  border: 1px solid #1e88e5;
  border-bottom: none;
  border-radius: 4px 4px 0 0;
  margin-right: 5px;
}

:deep(.el-tabs__content) {
  padding: 20px;
  background-color: white;
  border: 1px solid #1e88e5;
  border-radius: 0 0 4px 4px;
  border-top: none;
}
</style>
